package BFS.多源最短路问题;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Date 2024/9/10 21:31
 * @description: 从 0 到 1的距离
 * .    https://leetcode.cn/problems/01-matrix/
 * @Author LittleNight
 */
public class likou542 {

    // bfs 用标记数组和sz
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    int m, n;
    boolean[][] vis;
    public int[][] updateMatrix(int[][] mat) {
        m = mat.length; n = mat[0].length;
        vis = new boolean[m][n];
        int[][] dist = new int[m][n];
        Queue<int[]> queue = new LinkedList<>();
        // 1. 先添加所有的0. 添加0
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(mat[i][j] == 0) {
                    dist[i][j] = 0;
                    vis[i][j] = true;
                    queue.offer(new int[]{i, j});
                }
            }
        }
        // 2. bfs 主逻辑
        int step = 0;
        while(!queue.isEmpty()) {
            int sz = queue.size();
            step++; // 标记层数
            // 弹出下一层
            while(sz-- != 0) {
                int[] tmp = queue.poll();
                int a = tmp[0], b = tmp[1];
                for (int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
                        vis[x][y] = true; // 标记这个位置添加过
                        dist[x][y] = step;
                        queue.offer(new int[]{x, y}); // 添加到队列
                    }
                }
            }
        }
        return dist;
    }

}
